<template>
  <MainLayout>
    <div class="product-detail-content" v-if="product.id">
      <el-breadcrumb separator="/" style="margin-bottom: 20px">
        <el-breadcrumb-item><a href="/">首页</a></el-breadcrumb-item>
        <el-breadcrumb-item><a :href="`/category/${product.category}`">{{ categoryName }}</a></el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.name }}</el-breadcrumb-item>
      </el-breadcrumb>
      <el-row :gutter="40">
          <el-col :span="12">
            <el-image :src="product.image" :preview-src-list="[product.image]" fit="contain" style="width: 100%; height: 500px" />
          </el-col>
          <el-col :span="12">
            <h1>{{ product.name }}</h1>
            <el-divider />
            <p class="description">{{ product.description }}</p>
            <p class="price">¥{{ product.price }}</p>
            
            <div class="quantity-select">
              <label>数量：</label>
              <el-input-number v-model="quantity" :min="1" :max="99" />
            </div>

            <el-divider />

            <div class="actions">
              <el-button type="danger" size="large" @click="addToCart">加入购物车</el-button>
              <el-button type="warning" size="large" @click="buyNow">立即购买</el-button>
            </div>

            <el-divider />

            <el-tabs>
              <el-tab-pane label="商品详情" name="detail">
                <p>{{ product.description }}</p>
              </el-tab-pane>
              <el-tab-pane label="规格参数" name="specs">
                <el-table :data="specData" style="width: 100%">
                  <el-table-column prop="key" label="参数" width="150" />
                  <el-table-column prop="value" label="值" />
                </el-table>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>
    <div v-else style="text-align: center; padding: 100px 0;">
      <el-empty description="加载中..." />
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { productAPI } from '../api'
import { ElMessage } from 'element-plus'
import MainLayout from '../layouts/MainLayout.vue'

const route = useRoute()
const router = useRouter()

const product = ref({})
const quantity = ref(1)

const categoryMap = {
  'makeup': '美妆',
  'clothing': '服饰',
  'digital': '数码',
  'appliance': '电器',
  'fresh': '生鲜',
  'outdoor': '户外'
}

const categoryName = computed(() => categoryMap[product.value.category] || '')

const specData = ref([
  { key: '品牌', value: '自有品牌' },
  { key: '产地', value: '中国大陆' },
  { key: '保质期', value: '12个月' }
])

const fetchProduct = async () => {
  try {
    const response = await productAPI.getProductById(route.params.id)
    // 由于响应拦截器已经返回 response.data，所以直接使用
    if (response) {
      product.value = response
      specData.value[0].value = product.value.name.split(' ')[0] || '自有品牌'
    } else {
      ElMessage.error('商品不存在')
      router.push('/')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    if (error.response?.status === 404) {
      ElMessage.error('商品不存在')
      router.push('/')
    } else {
      ElMessage.error('获取商品详情失败，请检查服务器是否运行')
    }
  }
}

const addToCart = () => {
  const savedCart = localStorage.getItem('cart')
  let cartItems = savedCart ? JSON.parse(savedCart) : []
  
  // 检查是否已存在
  const existingItem = cartItems.find(item => item.id === product.value.id)
  if (existingItem) {
    existingItem.quantity += quantity.value
  } else {
    cartItems.push({ ...product.value, quantity: quantity.value })
  }
  
  localStorage.setItem('cart', JSON.stringify(cartItems))
  ElMessage.success('已添加到购物车')
}

const buyNow = () => {
  ElMessage.success('跳转到支付页面')
  // 实现购买逻辑
}

onMounted(() => {
  fetchProduct()
})
</script>

<style scoped>
.product-detail-content {
  width: 100%;
  max-width: 100%;
  padding: 0;
  box-sizing: border-box;
}

.description {
  font-size: 16px;
  color: #666;
  line-height: 1.8;
}

.price {
  font-size: 32px;
  color: #f56c6c;
  font-weight: bold;
}

.quantity-select {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 20px 0;
}

.actions {
  display: flex;
  gap: 20px;
}
</style>

